#include <iostream>
#include <string>
#include <pthread.h>
#include "Daemonize.h"
#include "RWBuffer.h"
#include "TeNetMgr.h"

/*
TReadWriteBuffer   kRWBuffer;

void* ReadThread(void* arg)
{   
    int fd = open("info.log",O_RDWR|O_CREAT|O_APPEND,0666);
    if(fd < 0)
    {
        return NULL;
    }
    while(1)//int i = 0;i < 1000;i++)
    {
        uint8 buf[20] = {};
        bool bRet = kRWBuffer.ReadBuffer(&buf,sizeof(buf));
        if(!bRet)
        {
            usleep(1);
            continue;        
        }
        write(fd,buf,sizeof(buf));
    }
    close(fd);
}

void* WriteThread(void* arg)
{
    int i=0;
    while(1)
    {
        uint8 buf[20] = {};
        sprintf((char*)buf,"%d:abcdefghi",i);
        if(kRWBuffer.WriteBuffer(&buf,sizeof(buf)))
        {
            ++i;
            usleep(1);           	   
            continue;
        }
        usleep(1);
    }
}
*/
class IServer : public TeNetCall
{
public:
    void Init()
    {
        kNetMgr.Init(this,2);

        bool bRet = kNetMgr.StartListen("0.0.0.0",1314,16,16);
        if(!bRet)
        {
            printf("Listen Fail [%d].\n",1314);
        }
        bRet = kNetMgr.StartListen("0.0.0.0",1315,16,16);
        if(!bRet)
        {
            printf("Listen Fail [%d].",1315);
        }
    }

    void Update()
    {
        kNetMgr.Update();
    }

    void OnAccept(int rkSock,const char* pcIP,int iPort)
    {
        printf("OnAccept one Connect.[%s:%d].\n",pcIP,iPort);
    }
    void OnConnected(int rkSock,const char* pcIP,int iPort)
    {
        printf("OnConnected one Connect.[%s:%d].\n",pcIP,iPort);
    }
    void OnRecv(int rkSock,void *pData,int iSize)
    {
        kNetMgr.SendData(rkSock,pData,iSize);
        //printf("Recv Data.[FD:%d],[SIZE:%d].\n",rkSock,iSize);
    }
    void OnDisConnect(int rkSocket)
    {
        printf("OnDisConnect.\n");
    }

private:
    TeNetMgr kNetMgr;

};

int main()
{
    //Daemonize kDaem;    
    //pthread_t id1,id2;
    //int i,ret;

    IServer kSer;
    kSer.Init();

    //ret=pthread_create(&id2,NULL,WriteThread,NULL);
    //ret=pthread_create(&id1,NULL,ReadThread,NULL);
    while(1)
    {
        kSer.Update();
        usleep(50);
    }
}
